/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package MailServer;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Logger;

/**
 *
 * @author lailiaidi
 */
public class SmtpServer extends Thread {

        private String obStrAddress;
        private int obIntPort;
        private int obIntMaxRequest;
        private ServerSocket obServerSocket;
        Socket obSocket;
        private Logger log;

        public SmtpServer(String obStrAddress, int obIntPort, int obIntMaxRequest) throws UnknownHostException, IOException {
            this.obStrAddress = obStrAddress;
            this.obIntPort = obIntPort;
            this.obIntMaxRequest = obIntMaxRequest;

            /*
             * Prepare to bind to an obStrAddress and obIntPort.
             */
            obServerSocket = new ServerSocket(obIntPort, obIntMaxRequest, InetAddress.getByName(obStrAddress));

            /*
             * Start our thread's processing.
             */
            start();
        }

        @Override
        public void run() {
            try {
                System.out.println("SMTP Listener started.");

                do {
                    /*
                     * Attempt to start listening for incoming connections.
                     */
                    try {
                        System.out.println("Accepting connections.");
                        obSocket = obServerSocket.accept();

                        Thread executor = new SmtpHandler(obSocket);
                        executor.start();
                    } catch (IOException e) {
                        System.out.format("An exception occured while attempting to listen for connections: %s", e.getMessage());
                        e.printStackTrace();
                        break;
                    }


                } while (true);
            } catch (Throwable e) {
                System.out.format("An exception occured during the listener loop: %s", e.getMessage());
            }
        }

        private void closeConnection() throws IOException {
            obSocket.close();
            obServerSocket.close();
        }
    }
